// pages/news/index/index.js
var call = require("../../../utils/request.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageStatus: false,
    page: 1,
    limit: 1,
    unreadTotal: 0, // 未读消息数
    listData: [], // 消息数据
    dataStatus: false, // 是否已经到底
    keyName: '', // 搜索字段
    saveKwd: '', // 保存搜索字段
    userInfo: {},
    isSearch: false,
    timer: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.cloud.init()
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo
    })
    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    wx.getSystemInfo({
      success: res => {
        let statusBarHeight = res.statusBarHeight // 状态栏的高度
        let navTop = menuButtonObject.top * 2
        let navObjWid = res.windowWidth - menuButtonObject.right + menuButtonObject.width // 胶囊按钮与右侧的距离 = windowWidth - right+胶囊宽度
        let navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
        let capsuleHeight = menuButtonObject.height * 2; //胶囊高度
        console.log(`导航栏总体高度${navHeight},胶囊距离顶部距离${navTop}.height,胶囊宽度(包括右边距离)${navObjWid}`)
        console.log(menuButtonObject)
        let contentHeight = capsuleHeight + navTop + 6 // 中间内容高度
        this.setData({
          navHeight,
          navTop,
          capsuleHeight,
          contentHeight
        })
      },
      fail(err) {
        console.log(err);
      }
    })

   
  },

  setTiming() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
    }
    let timer = setInterval(() => {
      if (this.data.keyName == '' || this.data.isSearch == false) {
        this.getList()
      } else {
        this.search()
      }
    }, 1000)
    this.setData({
      timer
    })
  },
  onShow() {
    // this.getListData()  // 获取消息数据
    this.getList()
    this.setTiming()
  },
  // 获取信息列表
  async getList() {
    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      "path": "/v1/chat" ,
      // "path": "/v1/chat/13183856657",
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    //  console.log(code,errorMsg,chatList,unReadNums)
    if (code == 1) {
      if (this.data.isSearch) {

      } else {
        this.setData({
          unreadTotal: data.unReadNums,
          listData: data.chatList
        })
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: errorMsg
      })
      if (this.data.timer) {
        console.log('卸载定时器');
        clearInterval(this.data.timer);
        this.setData({
          timer: null
        })
      }
    }
    this.setData({
      pageStatus: true,
      isSearch: false
    });
  },
  // 获取消息数据
  getListData(status) {
    let page = this.data.page // 当前页
    let limit = this.data.limit // 每页条数
    let keyName = this.data.keyName // 搜索
    call.httpData('GET', '/api/user/maillist', {
        page,
        limit,
        keyName
      },
      (res) => {
        console.log(res, '获取消息数据')
        if (res.code == 1) {
          let list = res.data.data
          let unreadTotal = res.data.unreadTotal
          this.setData({
            unreadTotal
          })

          if (status) { // 触发搜索
            let listData = this.data.listData // 数据
            listData = listData.concat(list)
            this.setData({
              listData
            })
          } else {
            this.setData({
              listData: list
            })
          }
          if (list.length < limit && page != 1) {
            this.setData({
              dataStatus: true
            })
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg
          })
        }
        this.setData({
          pageStatus: true
        });
        wx.hideToast() // 隐藏
      }, () => {
        doFail();
      })
  },
  /**
   * 页面上拉触底事件的处理函数，与点击加载更多做同样的操作
   */
  onReachBottom() {
    // let page = this.data.page; // 页码
    // let dataStatus = this.data.dataStatus
    // if (!dataStatus) {
    //   this.setData({
    //     page: page + 1
    //   })
    //   this.getListData(true) // 获取列表数据

    //   wx.showToast({
    //     title: '加载中...',
    //     icon: 'loading',
    //   })

    // }
  },
  // 清除全部未读
  async brush() {
    if(this.data.unreadTotal==0){
      wx.showToast({
        icon: 'none',
        title: '当前无未读消息'
      })
      return 
    }
    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      "path": "/v1/chat/readAll",
      // "path": "/v1/chat/13183856657",
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "put",
      "data": {
        "action": "inc"
      }
    })
    console.log(code, errorMsg, data, '清除全部未读');
    if (code == 1) {
      let listData = this.data.listData
      for (let list of listData) {
        list.unReadNums = 0
      }
      this.setData({
        unreadTotal: 0,
        listData
      })
      wx.showToast({
        icon: 'none',
        title: '已将所有消息标为已读'
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: errorMsg
      })
    }
    // call.httpData('GET', '/api/user/mailread', {},
    //   (res) => {
    //     console.log(res, '清除全部未读')
    //     if (res.code == 1) {
    //       let listData = this.data.listData
    //       for (let list of listData) {
    //         list.status = 1
    //       }
    //       this.setData({
    //         unreadTotal: 0,
    //         listData
    //       })
    //     } else {
    //       wx.showToast({
    //         icon: 'none',
    //         title: res.msg
    //       })
    //     }
    //   }, () => {
    //     doFail();
    //   })
  },
  // 去列表
  goDetails(e) {
    console.log(e.currentTarget.dataset);
    let {
      id,
      showname,
      couldreply
    } = e.currentTarget.dataset
    console.log(couldreply);
    if (couldreply == 0) {
      if (this.data.isSearch) {
        wx.navigateTo({
          url: '/pages/news/list/index?chatUUID=' + id + '&showName=' + showname + '&keyName=' + this.data.saveKwd + '&isSearch=true'
        })
      } else {
        wx.navigateTo({
          url: '/pages/news/list/index?chatUUID=' + id + '&showName=' + showname
        })
      }
    } else {
      console.log(this.data.isSearch);
      if (this.data.isSearch) {
        wx.navigateTo({
          url: '/pages/news/search/index?chatUUID=' + id + '&showName=' + showname + '&keyName=' + this.data.saveKwd + '&isSearch=true'
        })
      } else {
        wx.navigateTo({
          url: '/pages/news/service/index?chatUUID=' + id + '&showName=' + showname
        })
      }
    }
  },
  async search() {
    if (this.data.keyName == '') {
      wx.showToast({
        icon: 'none',
        title: '请输入搜索内容'
      })
      return false
    }

    let searchWords = this.data.keyName
    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      // "path": "/v1/chat/"+this.data.userInfo.mobile+"?searchWords=" + encodeURIComponent(searchWords),
      "path": "/v1/chat" + "?searchWords=" + encodeURIComponent(searchWords),
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc",
      }

    })
    console.log(code, data);
    if (code && code == 1) {
      if (data.chatList.length == 0) {
        wx.showToast({
          icon: 'none',
          title: '未搜索到消息'
        })
        this.setData({
          keyName: '',
          isSearch: false,
          unreadTotal: data.unReadNums,
        })
      } else {
        this.setData({
          listData: data.chatList,
          isSearch: true,
          saveKwd: searchWords,
          unreadTotal: data.unReadNums,
        })

      }
    } else {
      wx.showToast({
        icon: 'none',
        title: '未搜索到消息'
      })
      this.setData({
        keyName: ''
      })
    }
  },
  clear() {
    if (this.data.isSearch) {
      this.getList()
    }
  },
  input(e) {
    console.log(e.detail);
    if (e.detail == '') {
      this.getList()
    }
  },
  // 节流
  throttle: function (fn, context, delay, text) {
    clearTimeout(fn.timeoutId);
    fn.timeoutId = setTimeout(function () {
      fn.call(context, text);
    }, delay);
  },
  // 执行搜索
  queryData: function (name) {
    this.setData({
      page: 1,
      dataStatus: false
    })
    console.log(name) // 此处打印出来的就是 用户输入的值
    wx.showToast({
      title: '加载中...',
      icon: 'loading',
    })
    // this.getListData() // 获取列表数据

  },







  // 首页
  goHome() {
    wx.redirectTo({
      url: '/pages/home/index'
    })
  },
  // 工作
  goWork() {
    wx.redirectTo({
      url: '/pages/work/index/index'
    })
  },
  // 生活
  goLife() {
    wx.redirectTo({
      url: '/subPackages/pages/standard/home/index/index'
    })
  },
  // 我的
  goMy() {
    let userInfo = wx.getStorageSync('userInfo')  // 用户信息
    if(JSON.stringify(userInfo) == "{}"){
      let isSignIn = this.selectComponent('#isSignIn'); // 页面获取自定义组件实例
      isSignIn.isLogin(); // 通过实例调用组件事件
    }else{
      wx.redirectTo({
        url: '/pages/my/index/index'
      })
    }
  },
  onHide: function () {
    console.log('隐藏');
    if (this.data.timer) {
      console.log('卸载定时器');
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
    }
  },
  onUnload: function () {
    console.log('卸载');
    if (this.data.timer) {
      console.log('卸载定时器');
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
    }
  }
})